<?php
namespace app\index\controller;
use app\index\controller\BaseController;
use think\Db;
use think\Log;

class PayController extends BaseController {

	public function index() {
		cookie('URL', url());
		if (!cookie('USER')) {
			$this->redirect('Index/login');
		}
		$model = db("deposit")->where('uid', cookie('USER')['id'])->where('status', 2)->find();
		$this->assign('model', $model);
		return $this->fetch();
	}

	public function show() {
		return $this->fetch();
	}
	
	public function show2() {
		return $this->fetch();
	}
	
	public function dopayshop() {
		$sn= input('sn');
		$order = db('good_order')->where('order_sn', $sn)->where('status', 1)->find();
		
		// 拿到订单的订单编号
		$goodItems = db('order_items')->where('order_id', $order['id'])->select();
		if(empty($goodItems)){
			$this->error('未找到此订单的产品明细');
		}
		
		$log = db('paylog')->where('order_sn', $sn)->find();
		$userid = session('user_id');
		
		$price = $order['total_price'];
		if($userid=='60'){
			$price = 0.01;
		}	
		//查询用户信息
		$memberInfo = db('member')->where('user_Id',$userid)->find();
		
		
		$pay_type = $order['pay_type'];
		//商户订单号，商户网站订单系统中唯一订单号，必填
		$out_trade_no = $order['order_sn'];
		$subject = '懒狗';
		//付款金额，必填
		$total_amount = $price;
		//商品描述，可空
		$body = $order['memo'];
		// 业务逻辑
		$data['user_id']  = $userid;
		$data['agent_id'] = $order['agent_id'];
		$data['balance'] = $total_amount;
		$data['order_type']  = 2;
		$data['order_sn'] = $out_trade_no;
		$data['pay_type'] = $pay_type;
		$data['state'] = 1;
		$data['message'] = '商城下单';
		$data['order_id'] = $order['id'];
		$data['add_time'] = now_time();
		$data['pay_time'] = now_time();

		//H5支付
		if ($pay_type == 4) {
			if (!$log) {
				$data['pay_type'] = 1;
				db('paylog')->insert($data);
			}
			// 此处根据实际业务情况生成订单 然后拿着订单去支付
			//$url = url('dingyue/wxpaywithh5', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
			// 商城购买的时候不能跟杂志订阅的支付共用一个，因为支付成功后的回调业务不一样。
			$url = url('pay/wxpaywithh5s', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
			// 前往支付
			$this->redirect($url);
		
		//微信客户端支付	
		}else if ($pay_type == 1) {
			if (!$log) {
				$data['pay_type'] = 1;
				db('paylog')->insert($data);
			}
			// 此处根据实际业务情况生成订单 然后拿着订单去支付
			$url = url('pay/wxpay', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
			// 前往支付
			$this->redirect($url);
		
		//支付宝支付
		} elseif ($pay_type == 3) {
			if (!$log) {
				$data['pay_type'] = 2;
				db('shop_paylog')->insert($data);
			}
			//超时时间
			$timeout_express = "1m";
			$payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
			$payRequestBuilder->setBody($body);
			$payRequestBuilder->setSubject($subject);
			$payRequestBuilder->setOutTradeNo($out_trade_no);
			$payRequestBuilder->setTotalAmount($total_amount);
			$payRequestBuilder->setTimeExpress($timeout_express);
			$config = config('alipay');
			$payResponse = new \AlipayTradeService($config);
			$result = $payResponse->wapPay($payRequestBuilder, $config['return_urls'], $config['notify_urls']);
			return;
		} else {
			$this->error('支付方式不存在');
		}
		
	}

	public function wxpay() {
		// 导入微信支付sdk
		$wxpay = new \weixinpay\Weixinpay();
		// 获取jssdk需要用到的数据
		$data = $wxpay->getParameters();		
		// 将数据分配到前台页面
		return $this->fetch('', array('data' => json_encode($data),'total_fee' => input('total_fee')));
	}

	/**
	 * notify_url接收页面
	 */
	public function wxpay_notify() {
		// 获取xml
		$xml = file_get_contents('php://input', 'r');
		//转成php数组 禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		$data = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
		// 导入微信支付sdk
		$wxpay = new \weixinpay\Weixinpay();
		$result = $wxpay->notify();
		if ($result) {
			// 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单id
			Log::record('>>>>>>1wxpay_notify:'.$result['result_code'],'info');
			$paylog = db('good_order')->where('order_sn', $result['out_trade_no'])->find();
			Log::record('>>>>>>1','info');
			if (empty($paylog)) {
				Log::record('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>2查询到的支付日志'.$paylog['id'],'info');
				//$this->processError('订单不存在');
				$this->error('订单不存在');
			}
			Log::record('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>3查询到的支付日志','info');
			$this->orderHandle($paylog);
			
			$this->redirect(url('pay/pay_success?sn='.$result['out_trade_no']));
			
		}
	}

	// 2.订单处理
	protected function orderHandle($paylog) {
		//file_put_contents('b.txt', $paylog['order_sn']);
		if ($paylog['status'] == 1) {
			// 判断订单状态, 如果订单未做过处理, 则处理自己核心业务
			$result = true;
			
			Db::startTrans();
			
			$handlerResult1 = db('paylog')->where('order_sn', $paylog['order_sn'])->update(array(
				'state' => 2,
				'pay_time' => now_time()
			));			
			if(!$handlerResult1)$result = false;
			
			$handlerResult2 = db('good_order')->where('order_sn', $paylog['order_sn'])->update(array(
				'status' => 2,
				'pay_time' => now_time()
			));
			if(!$handlerResult2)$result = false;


			//查询用户信息
			$members = db('member')->where('user_id', $paylog['user_id'])->find();
			
			//检查会员是否抵扣 true 有 fasle 没有
			$flag = check_money($members);	
			if($flag || $flag==1){
				//添加会员资金变化日志
				$data['user_id'] = $members['user_id'];
				$data['balance'] = $members['money']; //变化金额
				$data['order_sn'] = $paylog['order_sn']; // 订单号  提现无订单
				$data['order_type'] = 2; //类型  1支付红包 2 余额抵扣
				$data['message'] = '会员余额抵扣';//消息
				$data['add_time'] = now_time();	
				$rest = db('member_charge')->insert($data);	
							
				$total_money = $members['total_dk_money'] + $members['money'];
				//提交成功，则需对会员的余额先扣除，以防会员重复提交提现申请
				$rest2 = db('member')->where('user_id', $paylog['user_id'])->update(array('money' => 0,'total_dk_money' => $total_money));
			}

			//推荐分佣
				$rest5 = db('order_items')->where('order_id', $handlerResult2['id'])->select();
				
				foreach($rest5 as $i){
					if($i['tui_id']){
						$memberpid = db('member')->where('user_id', $i['tui_id'])->find();
						if($memberpid && $memberpid['denji'] == 3){
							$numpid = $i['tui_price'];
							$datapid['user_id'] = $memberpid['user_id'];
							$datapid['balance'] = $numpid; //变化金额
							$datapid['order_sn'] = $order['order_sn']; // 订单号  提现无订单
							$datapid['order_type'] = 1; //类型  1支付红包 //1提现2二维码付款3提现失败4返现5分佣
							$datapid['message'] = '会员商品推荐奖励';//消息
							$datapid['add_time'] = now_time();	
							$restpid = db('member_charge')->insert($datapid);	
							$yue_moneypid = $memberpid['money'] + $numpid;
							$rest4 = db('member')->where('user_id', $memberpid['user_id'])->update(array('money' => $yue_moneypid));
						}
					}
					
				}
			//更新完订单的状态后，需要将该订单所获取的积分给到购买的会员用户end
			//个人分配奖金
			//会员余额变化日志
			$member = db('member')->where('user_id', $paylog['user_id'])->find();
			$num = rand(10,20)/100;
			//添加会员资金变化日志
			$data['user_id'] = $paylog['user_id'];
			$data['balance'] = $num; //变化金额
			$data['order_sn'] = $paylog['order_sn']; // 订单号  提现无订单
			$data['order_type'] = 1; //类型  1支付红包 //1提现2二维码付款3提现失败4返现5分佣
			$data['message'] = '会员支付红包';//消息
			$data['add_time'] = now_time();	
			$rest = db('member_charge')->insert($data);	
				
			$yue_money = $member['money'] + $num;
			$total_money = $member['total_income'] + $num;
			//提交成功，则需对会员的余额先扣除，以防会员重复提交提现申请
			$rest3 = db('member')->where('user_id', $member['user_id'])->update(array('money' => $yue_money,'total_income' => $total_money));
			
			if($result){
				// 提交事务
			    Db::commit();    
				
			}else{
				// 回滚事务
			    Db::rollback();
			    $this->error('支付失败',url('member/index'));
			}
			return $result;
		}
	}
	
	public function pay_success(){
		$rest3 = db('member_charge')->where('user_id', session('user_id'))->where('order_type', 1)->order('add_time desc')->limit(1)->select();
		$this->assign('money',round($rest3[0]['balance'],2));
		return $this->fetch();
	}
	
	
	
	public function dopayshenji() {
		$sn= input('sn');
		$order = db('order_shenji')->where('order_sn', $sn)->where('status', 1)->find();
		
		$userid = session('user_id');
		//查询用户信息
		$memberInfo = db('member')->where('user_Id',$userid)->find();
		//商户订单号，商户网站订单系统中唯一订单号，必填
		$out_trade_no = $order['order_sn'];
		$subject = '懒狗';
		//付款金额，必填
		$total_amount = $order['money'];
		//商品描述，可空
		$body = $order['memo'];
		// 此处根据实际业务情况生成订单 然后拿着订单去支付
		$url = url('pay/wxpayl', array('out_trade_no' => $out_trade_no,'total_fee' => $total_amount));
		// 前往支付
		$this->redirect($url);
		
	}
	
	public function wxpayl() {
		// 导入微信支付sdk
		$wxpay = new \weixinpay\Weixinpayx();
		// 获取jssdk需要用到的数据
		$data = $wxpay->getParameters();
		// 将数据分配到前台页面
		return $this->fetch('', array('data' => json_encode($data),'total_fee' => input('total_fee')));
	}

	/**
	 * notify_url接收页面
	 */
	public function wxpay_notifyx() {
		// 获取xml
		$xml = file_get_contents('php://input', 'r');
		//转成php数组 禁止引用外部xml实体
		libxml_disable_entity_loader(true);
		$data = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
		// 导入微信支付sdk
		$wxpay = new \weixinpay\Weixinpayx();
		$result = $wxpay->notify();
		if ($result) {
			// 验证成功 修改数据库的订单状态等 $result['out_trade_no']为订单id
			Log::record('>>>>>>1wxpay_notify:'.$result['result_code'],'info');
			$paylog = db('order_shenji')->where('order_sn', $result['out_trade_no'])->find();
			Log::record('>>>>>>1','info');
			if (empty($paylog)) {
				Log::record('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>2查询到的支付日志'.$paylog['id'],'info');
				//$this->processError('订单不存在');
				$this->error('订单不存在');
			}
			Log::record('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>3查询到的支付日志','info');
			$this->orderHandlex($paylog);
			
			$this->redirect(url('pay/pay_successl?sn='.$result['out_trade_no']));
			
		}
	}

	// 2.订单处理
	protected function orderHandlex($paylog) {
		
		if ($paylog['status'] == 1) {
			// 判断订单状态, 如果订单未做过处理, 则处理自己核心业务
			$result = true;
			
			Db::startTrans();
			
			
			$handlerResult2 = db('order_shenji')->where('order_sn', $paylog['order_sn'])->update(array(
				'status' => 2,
				'pay_time' => now_time()
			));
			if(!$handlerResult2)$result = false;
	

			//查询用户信息
			
			$data['denji'] = 3; 
			$data['update_time'] = now_time();	
			$rest = db('member')->where('user_id', $paylog['uid'])->update($data);	
			if(!$rest)$result = false;
			//file_put_contents('b.txt', $paylog['uid']);
			$members = db('member')->where('user_id', $paylog['uid'])->find();
			if($members['pid1']){
				$rest2 = db('member')->where('user_id', $members['pid1'])->setInc('money',100);
				$data3['balance'] = 100;
				$data3['user_id'] = $members['pid1'];
				$data3['order_type'] = 4;
				$data3['order_sn'] = $paylog['order_sn'];
				$data3['message'] = '会员升创业奖励100';
				$data3['add_time'] = now_time();
				$rest3 = db('member_charge')->insert($data3);
			}
			
			if($result){
				// 提交事务
			    Db::commit();    
				
			}else{
				// 回滚事务
			    Db::rollback();
			    $this->error('支付失败',url('member/index'));
			}
			return $result;
		}
	}
	
	public function pay_successl(){
		return $this->fetch();
	}
}

